package vn.com.epi.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This servlet provides various information about recommendations. It is handy
 * for developing and debuging but not to be used in production.
 */
@WebServlet("/list-files.html")
public class ListFileServlet extends HttpServlet {
    
    
    private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListFileServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("path");
        if (path == null) {
            request.getRequestDispatcher("/WEB-INF/jsp/list-files-form.jsp")
                    .forward(request, response);
            return;
        }
        List<String> list = new ArrayList<String>();
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) 
            list.add(listOfFiles[i].getName());
        try {
            request.setAttribute("path", path);
            request.setAttribute("lines", list);
            request.getRequestDispatcher("/WEB-INF/jsp/content.jsp").forward(request, response);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

}
